#  -*- coding: utf-8 -*-

from strategy.stock_pool.base_stock_pool import BaseStockPool
from factor.factor_module import FactorModule
from data.data_module import DataModule
from util.stock_util import get_trading_dates,get_all_codes_date,get_diff_dates,calc_negative_diff_dates,calc_positive_diff_dates,multi_computer,get_all_codes_trading_date,get_code_name
from pandas import DataFrame,Series
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import scipy.signal as signal
import time
from sklearn import linear_model
import pickle
import os
from util.database import DB_CONN
from pymongo import UpdateOne,ASCENDING


"""
趋势加速策略股票池定义
A:波段1起点（极小值）；
B：波段1终点（加速前一天）；
C：加速第一天（转折点）；
D：当前日

"""

names = ['date', 'code', 'date_A', 'date_B', 'date_C',
         'avg_2', 'avg_3', 'change_rate_AB', 'diff_dates', 'daily_change_rate_AB', 'ratio_above_20_AB',
         'ratio_positive_AB','change_rate_above_5_days_AB','change_rate_above_5_ratio_AB',
         'change_rate_below_N5_days_AB','change_rate_below_N5_ratio_AB','var_AB','change_rate_mean_AB',
         'positive_continue_value', 'negative_continue_value', 'amount_mean_AB',
         'amount_mean_CD', 'positive_mean_amount', 'negative_mean_amount']

class TrendingSpeedUpStockPool(BaseStockPool):


    def multi_get_trending_speedup_stock(self,date):
        start_time = time.time()
        all_codes = get_all_codes_trading_date(date)
        args =(date,)
        option_codes_dict = dict()
        option_codes_multi_lst = multi_computer(get_trending_speedup_stock_at_date,all_codes,args)
        #print(option_codes_multi_lst)
        for codes_dict in option_codes_multi_lst:
            #print(codes_dict)
            option_codes_dict.update(codes_dict)

        #特征数据存放入数据库，存入之前先要把同时期的数据删掉
        collection = DB_CONN["trending_speedup_strategy_feature"]
        collection.create_index([('code', 1), ('date', 1)])
        collection.create_index([('date', 1)])
        collection.remove({"date":date})

        update_requests = []
        for key,value in option_codes_dict.items():
            update_requests.append(
                UpdateOne(
                    {'code': value['code'], 'date': value['date']},
                    {'$set': value},
                    upsert=True)
            )
        #print(update_requests)
        # 批量写入，提高访问效率
        if len(update_requests) > 0:
            start_time = time.time()
            update_result = collection.bulk_write(update_requests, ordered=False)
            end_time = time.time()
            print('保存speedup策略特征数据到数据集：%s，日期： %s, 插入：%4d条, 更新：%4d条,耗时：%.3f 秒' %
                  (collection.name, date, update_result.upserted_count, update_result.modified_count,(end_time-start_time)),
                  flush=True)

        self.fiilup_future_result_at_date(date)
        self.fillup_public_feature_data_at_date(date)

        end_time = time.time()
        #print(option_codes_dict)
        print("多进程执行趋势加速策略选股，日期：%s,候选股票：%s,耗时：%.2f" %(date,option_codes_dict.keys(),(end_time - start_time)))

        return option_codes_dict

    def fiilup_future_result_at_date(self,date):
        # 找出过去的日期的股票列表，计算到目前时间的区间涨幅跌幅,并存入数据库
        dm = DataModule()
        #20天涨跌幅
        past_date = calc_negative_diff_dates(code="999999",is_index=True, date=date, delta_days=-20)
        collection = DB_CONN["trending_speedup_strategy_option_stocks"]
        past_date_data = collection.find_one({'date': past_date})
        if past_date_data is None or 'option_stocks' not in past_date_data.keys():
            print(f"{past_date}:没有数据！")
            return
        codes = past_date_data['option_stocks']
        update_requests = []
        for code in codes:
            print(f"查找 {past_date}:{code}特征数据！")

            result_dict = dict()
            buy_date = calc_positive_diff_dates(code=code, date=past_date, delta_days=1)

            code_df = dm.get_k_data(code, index=False, autype="hfq", begin_date=buy_date, end_date=date)
            if code_df.index.size == 0:
                continue
            code_df.set_index(['date'], inplace=True)
            #print(code_df)
            #先找整个区间最大值，再找起始日到最大日之间的最小值
            close_ser = code_df["close"]
            #beg_min = code_df.loc[past_date]['low']
            #买入日的开盘价
            beg_open = code_df.loc[buy_date]['open']

            max_value = close_ser.max()
            max_idx = close_ser.idxmax()
            max_diff_dates = get_diff_dates(code,buy_date,max_idx)
            #print("maxidx: %s,max_value: %s" %(max_idx,max_value))
            code_to_max_df = code_df.loc[buy_date:max_idx]
            min_value = code_to_max_df['close'].min()
            min_idx = code_to_max_df['close'].idxmin()
            min_diff_dates =  get_diff_dates(code,buy_date,min_idx)
            #print("min_idx: %s,min_value: %s" %(min_idx,min_value))

            max_change_rate = round(100 * (max_value - beg_open)/beg_open,2)
            min_change_rate = round(100 * (min_value - beg_open)/beg_open,2)

            # #print(diff_dates,max_change_rate,min_value,beg_min)
            #最大值日2个交易日（保证可卖出），最大值收益超过8%，最小值不低于起始日的最低价（大阳底部）
            # if diff_dates >= 1 and max_change_rate >= 8  and min_value >= beg_min :
            #     code_feature_df.loc[i,"Y"] = 1
            result_dict['max_change_rate'] = max_change_rate
            result_dict['min_change_rate'] = min_change_rate
            result_dict['max_diff_dates'] = max_diff_dates
            result_dict['min_diff_dates'] = min_diff_dates

            update_requests.append(
                UpdateOne(
                    {'code': code, 'date': past_date},
                    {'$set': result_dict},
                    upsert=True)
            )
        # 批量写入，提高访问效率
        collection = DB_CONN["trending_speedup_strategy_feature"]
        if len(update_requests) > 0:
            start_time = time.time()
            update_result = collection.bulk_write(update_requests, ordered=False)
            end_time = time.time()
            print('更新speedup策略特征数据到数据集：%s，日期： %s, 插入：%4d条, 更新：%4d条,耗时：%.3f 秒' %
                  (collection.name, past_date, update_result.upserted_count, update_result.modified_count,
                   (end_time - start_time)),
                  flush=True)
        return

    def fillup_public_feature_data_at_date(self,date):
        #补充大盘公共数据到个股特征里
        start_time = time.time()
        main_index_collection = DB_CONN['main_index']
        main_index_data = main_index_collection.find_one(
            {'date': date},
            projection={'_id': False,'date':False})
        if main_index_data is None:
            print(f"{date}日没有大盘数据！")
            return
        # print(main_index_data)
        option_collection = DB_CONN["trending_speedup_strategy_option_stocks"]
        option_date_data = option_collection.find_one({'date': date})
        if option_date_data is None or 'option_stocks' not in option_date_data.keys():
            print(f"{date}日没有候选股票数据！")
            return
        codes = option_date_data['option_stocks']
        update_requests = []
        for code in codes:
            update_requests.append(
                UpdateOne(
                    {'code': code, 'date': date},
                    {'$set': main_index_data},
                    upsert=True)
            )

        collection = DB_CONN["trending_speedup_strategy_feature"]

        if len(update_requests) > 0:
            update_result = collection.bulk_write(update_requests, ordered=False)

            end_time = time.time()
            print(f'填充大盘:{date}日因子数据，插入{update_result.upserted_count}条，更新：{update_result.modified_count}条,'
                  f'耗时：{end_time - start_time}秒',
                  flush=True)
        return

    def export_feature_data(self):
        feature_collection = DB_CONN[f'{self.strategy_name}_strategy_feature']
        daily_cursor = feature_collection.find(
            {'date': {'$gte': self.begin_date, '$lte': self.end_date}},
            sort=[('date', ASCENDING)],
            projection={'_id': False})
        feature_data_df = DataFrame([x for x in daily_cursor])
        feature_data_df.set_index("code", inplace=True)
        feature_data_df.to_csv(f"{self.stock_pool_path}/{self.strategy_name}_{self.begin_date}_{self.end_date}_feature.csv",encoding="UTF-8_sig")
        return

    def get_option_stocks(self):
        """
        实现股票池选股逻辑，找到指定日期范围的候选股票
        条件：0 < PE < 30, 按从小到大排序，剔除停牌后，取前100个；再平衡周期：7个交易日
        :return: tuple，再平衡的日期列表，以及一个dict(key: 再平衡日, value: 当期的股票列表)
        """

        dm = DataModule()

        # 获取日期范围的交易日历
        all_dates = get_trading_dates(self.begin_date, self.end_date)

        # 缓存股票和其对应有交易的日期
        code_dates_cache = dict()

        # 调整日和其对应的股票
        rebalance_date_codes_dict = dict()
        rebalance_dates = []

        # 保存上一期的股票池
        last_phase_codes = []
        # 所有的交易日数
        dates_count = len(all_dates)

        # 记录股票池里股票的特征数据
        code_feature_df = pd.DataFrame(columns=names)

        # 用再平衡周期作为步长循环
        update_requests = []
        for index in range(0, dates_count, self.interval):
            # 当前的调整日
            rebalance_date = all_dates[index]
            print(rebalance_date)
            self.logger.info('调整日：' + rebalance_date)

            # 获取本期符合条件的备选股票
            this_phase_option_codes_dict = self.multi_get_trending_speedup_stock(rebalance_date)
            #this_phase_option_codes = get_trending_stock_at_date(None,rebalance_date)
            this_phase_option_codes = list(this_phase_option_codes_dict.keys())
            option_codes_copy = this_phase_option_codes.copy()
            self.logger.info('原始备选股票')
            this_phase_option_codes.sort()
            self.logger.info(this_phase_option_codes)

            # 本期入选的股票代码列表
            this_phase_codes = []

            # 找到在上一期的股票池，但是当前停牌的股票，保留在当期股票池中
            if len(last_phase_codes) > 0:
                print("上一期股票池个数：%4d" % len(last_phase_codes))
                for code in last_phase_codes:
                    if code not in list(code_dates_cache.keys()):
                        daily_ks = dm.get_k_data(code, autype=None,index = False, begin_date=self.begin_date, end_date=self.end_date)
                        daily_ks.set_index(['date'], inplace=True)
                        # 只保留交易日的数据
                        daily_ks = daily_ks[daily_ks['is_trading'] == True]
                        code_dates_cache[code] = list(daily_ks.index)

                    if rebalance_date not in code_dates_cache[code]:
                        this_phase_codes.append(code)


            self.logger.info('上期停牌的股票')
            this_phase_codes.sort()
            self.logger.info(this_phase_codes)

            # 剩余的位置用当前备选股票的,先去重
            for dup_code in this_phase_codes:
                if dup_code in this_phase_option_codes:
                    this_phase_option_codes.remove(dup_code)

            option_size = len(this_phase_option_codes)
            if option_size > (100 - len(this_phase_codes)):
                this_phase_codes += this_phase_option_codes[0:100 - len(this_phase_codes)]

            else:
                this_phase_codes += this_phase_option_codes

            # 当期股票池作为下次循环的上期股票池
            last_phase_codes = this_phase_codes

            # 保存到返回结果中
            rebalance_date_codes_dict[rebalance_date] = this_phase_codes
            rebalance_dates.append(rebalance_date)

            self.logger.info('当前最终的备选票：%s' % rebalance_date)
            this_phase_codes.sort()
            self.logger.info(this_phase_codes)

            #存入数据库
            update_requests.append(
                UpdateOne(
                    {'date': rebalance_date},
                    {'$set': {"date":rebalance_date,"stocks":rebalance_date_codes_dict[rebalance_date],
                              "option_stocks":option_codes_copy}},
                    upsert=True)
            )

        # 批量写入，提高访问效率
        collection = DB_CONN["trending_speedup_strategy_option_stocks"]
        collection.create_index([('date', 1)])
        if len(update_requests) > 0:
            start_time = time.time()
            update_result = collection.bulk_write(update_requests, ordered=False)
            end_time = time.time()
            print('保存speedup策略特征数据到数据集：%s，插入：%4d条, 更新：%4d条,耗时：%.3f 秒' %
                  (collection.name, update_result.upserted_count, update_result.modified_count,(end_time-start_time)),
                  flush=True)

        return rebalance_dates, rebalance_date_codes_dict


def insert_feature_data_at_date(code,date):

    feature_dict = dict()
    fm = FactorModule()

    #rs数据
    date_rs_df = fm.get_single_stock_factors(code, "rs", False, date, date)
    if len(date_rs_df) == 1 and "rs_250" in date_rs_df.columns.values:
        feature_dict["date_C_rs_60"] = date_rs_df.loc[0]['rs_60']
        feature_dict["date_C_rs_120"] = date_rs_df.loc[0]['rs_120']
        feature_dict["date_C_rs_250"] = date_rs_df.loc[0]['rs_250']


    return feature_dict



def get_trending_speedup_stock_at_date(codes,date):
    start_time = time.time()
    option_codes_dict = dict()
    fm = FactorModule()
    if codes == None:
        codes = ['300573']

    dm = DataModule()
    change_rate_minimum = 4
    speed_2_dates = 6
    speed_3_dates = 5
    change_rate_min_for_AB = 25
    daily_change_rage_max_for_AB = 1.5
    last_dates_for_AB = 20
    ratio_above_20_min_for_AB = 75
    for code in codes:

        try:
            #每次循环需要建一个新的对象，否则赋值后下一个循环会被覆盖掉，从而影响保存的值
            #code_data_s = pd.Series(index=names)
            code_data_s = dict()

            print("开始计算股票：%s的趋势" % code)
            # 取近半年k线数据
            begin_date = calc_negative_diff_dates(code=None,date = date,delta_days = -120)
            if begin_date == False:
                begin_date = None

            code_df = dm.get_k_data(code,index=False,autype="hfq",begin_date=begin_date,end_date=date)

            if code_df.index.size == 0:
                continue

            code_df.set_index(['date'], inplace=True)
            #print(code_df.head())
            # 1.当日大涨，近3天平均涨幅>6,或近2天平均涨幅>7,然后找到3天或2天加速的前一天B，涨幅 < 4;
            date_speedup = calc_negative_diff_dates(code=code,date = date,delta_days = -3)
            #print(date_speedup)
            change_rate_df = fm.get_single_stock_factors(code,"change_rate",False,date_speedup,date)
            #print(change_rate_df)

            if len(change_rate_df) == 4:
                change_rate_0 = change_rate_df.loc[0]['close_change_rate']
                change_rate_1 = change_rate_df.loc[1]['close_change_rate']
                change_rate_2 = change_rate_df.loc[2]['close_change_rate']
                change_rate_3 = change_rate_df.loc[3]['close_change_rate']
                avg_3 = round((change_rate_1+change_rate_2+change_rate_3)/3,2)
                avg_2 = round((change_rate_2+change_rate_3)/2,2)

            #当日涨幅小
            if round(change_rate_3,1) < change_rate_minimum:
                continue


            print("S1:当日涨幅：%.2f,近2日平均涨幅：%.2f,近3日平均涨幅：%.2f"
                  % (change_rate_3,avg_2,avg_3))

            #近2天大于7，之前一天小于4 或3天大于6，之前一天小于4
            if avg_2 > speed_2_dates and round(change_rate_1,1) < change_rate_minimum:
                date_B = change_rate_df.loc[1]['date']
                date_C = change_rate_df.loc[2]['date']

            elif avg_3 > speed_3_dates and round(change_rate_0,1) < change_rate_minimum:
                date_B = change_rate_df.loc[0]['date']
                date_C = change_rate_df.loc[1]['date']
            else:
                continue


            # 2，再往前找第一个极小值A
            extrem_date_index = []
            extrem_date_values = []
            close_array = code_df["close"]
            code_df['ma20'] = code_df["close"].rolling(20).mean()
            close_np = close_array.values

            extrem_max_index = signal.argrelextrema(close_np, np.greater, order=15)[0]
            extrem_min_index = signal.argrelextrema(-close_np, np.greater, order=15)[0]

            extrem_max_date_index = code_df.index[extrem_max_index]
            extrem_min_date_index = code_df.index[extrem_min_index]

            #极大值，极小值都加入同一个列表
            [extrem_date_index.append(x) for x in extrem_max_date_index]
            [extrem_date_index.append(x) for x in extrem_min_date_index]
            #降序排序,值的顺序与排序后的日期顺序相同
            extrem_date_index.sort(reverse = True)
            [extrem_date_values.append(code_df.loc[x]['close']) for x in extrem_date_index]

            #极值序列第一个值就是极小值，且相隔时间大于20天（一个月交易日）.第一个值就是极小值也排除了中间有其他极大值的情况
            #print(extrem_date_index[0])
            if extrem_date_index[0] not in extrem_min_date_index:
                continue
            date_A = extrem_date_index[0]

            # 3，AB段涨幅 > 30, 持续天数 > 20,日均涨幅范围待定
            diff_dates = get_diff_dates(code,date_A,date_B)
            date_A_close = code_df.loc[date_A]['close']
            date_B_close = code_df.loc[date_B]['close']
            change_rate_AB = 0
            daily_change_rate_AB = 0
            if diff_dates != 0 and date_A_close != 0 :
                change_rate_AB = round(100*(date_B_close - date_A_close)/date_A_close,2)
                daily_change_rate_AB = round(change_rate_AB/diff_dates,2)

            print("S2-3:dateA：%s,dateB: %s,AB段涨幅%.2f,AB段持续时间：%d,日均涨幅：%.2f"
                  % (date_A,date_B,change_rate_AB,diff_dates,daily_change_rate_AB))

            if diff_dates < last_dates_for_AB or change_rate_AB < change_rate_min_for_AB\
                    or daily_change_rate_AB > daily_change_rage_max_for_AB:
                continue


            # 4，AB段没有大涨大跌的，或很少, 基本稳定在20日线上（稳定在20日线上个数比例 > ?）阳聚阴散,阳多阴少
            change_rate_AB_df = fm.get_single_stock_factors(code,"change_rate",False,date_A,date_B)
            change_rate_mean_AB = round(change_rate_AB_df["close_change_rate"].mean(),2)
            change_rate_above_0 = change_rate_AB_df.loc[change_rate_AB_df["close_change_rate"] > 0,"close_change_rate"].count()
            change_rate_above_5 = change_rate_AB_df.loc[change_rate_AB_df["close_change_rate"] > 5,"close_change_rate"].count()
            change_rate_below_N5 = change_rate_AB_df.loc[change_rate_AB_df["close_change_rate"] < -5,"close_change_rate"].count()
            var_AB = round(change_rate_AB_df["close_change_rate"].var(),2)
            ratio_positive_AB = round(100*change_rate_above_0/diff_dates,2)
            change_rate_above_5_ratio_AB = round(100*change_rate_above_5/diff_dates,2)
            change_rate_below_N5_ratio_AB = round(100*change_rate_below_N5/diff_dates,2)

            #计算阳聚阴散
            last_positive_flag = 0
            last_negative_flag = 0
            positive_continue_value = 0
            negative_continue_value = 0
            positive_dates = list()
            negative_dates = list()

            #print(change_rate_AB_df)
            for tmp in change_rate_AB_df.itertuples():
                tmp_date = getattr(tmp,"date")
                tmp_change_rate = getattr(tmp,"close_change_rate")
                if tmp_change_rate > 0 and last_positive_flag == 1:
                    positive_continue_value += 1

                elif tmp_change_rate <= 0 and last_negative_flag == 1:
                    negative_continue_value += 1

                if tmp_change_rate > 0:
                    last_positive_flag = 1
                    last_negative_flag = 0
                    positive_dates.append(tmp_date)
                else:
                    last_positive_flag = 0
                    last_negative_flag = 1
                    negative_dates.append(tmp_date)
            #print(positive_dates)
            #20日线上方比例,9成以上
            hfq_ma_AB_df = fm.get_single_stock_factors(code,"hfq_ma",False,date_A,date_B)
            hfq_ma_AB_df.set_index(['date'], inplace=True)
            code_AB_df = code_df[date_A:date_B]
            diff_close_ma20_AB_df = code_AB_df['close'] - hfq_ma_AB_df['ma20']
            AB_above_ma20_cnt = diff_close_ma20_AB_df[diff_close_ma20_AB_df>0].count()
            ratio_above_20_AB = round(100*AB_above_ma20_cnt/diff_dates,2)

            print("S4:AB段收盘价在20日线上方的天数比例：%.2f,收阳天数：%.2f,阳线比例: %.2f，连续阳线值：%d,连续阴线值：%d,"
                  "涨幅大于5天数：%.2f,大于5比例：%.2f,小于-5天数：%.2f,小于-5比例：%.2f,涨幅方差：%.2f,涨幅均值：%.2f"
                  %(ratio_above_20_AB,change_rate_above_0,ratio_positive_AB,positive_continue_value,negative_continue_value,
                    change_rate_above_5,change_rate_above_5_ratio_AB,change_rate_below_N5,change_rate_below_N5_ratio_AB,var_AB,change_rate_mean_AB))

            if ratio_above_20_AB < ratio_above_20_min_for_AB or ratio_positive_AB < 50 or positive_continue_value < negative_continue_value:
                continue
            # 5，AB段MA20拟合斜率，方差小

            # 7，当日光头大阳线，上影线排除
            # 8. AB量能比之前大，比之后小,CD明显放量（大于AB段量能，例外情况是一字板也可以不计算量能）；阳放阴缩还没做
            amount_mean_AB= code_df.loc[date_A:date_B,"amount"].mean()
            amount_mean_CD= code_df.loc[date_C:date,"amount"].mean()
            #print(code_df.loc[positive_dates,"amount"])
            positive_mean_amount = code_df.loc[positive_dates,"amount"].mean()
            negative_mean_amount = code_df.loc[negative_dates,"amount"].mean()

            change_rate_amount_AB_BC = round(100 * (amount_mean_CD - amount_mean_AB)/amount_mean_AB,2)
            print("S5:波段1(AB)平均成交额：%.2f亿元,波段2(CD)平均成交额：%.2f亿元,差值比例: %.2f,阳线平均成交量：%.2f亿元，阴线平均成交量：%.2f亿元"
                  %(amount_mean_AB/1E8,amount_mean_CD/1E8,change_rate_amount_AB_BC,positive_mean_amount/1E8,negative_mean_amount/1E8))
            if amount_mean_AB > amount_mean_CD :
                print("S5: AB量能比CD高，不满足CD段明显比AB段放量的条件")
                continue

            #第二步，找出最近的极大值极小值点,计算波段1和波段2涨跌幅，
            #波段1涨幅>50,波段2回调<30
            #最近5天的20日线拟合斜率向上
            #C点到D点的拟合斜率向上

            # clf = linear_model.LinearRegression()
            # date_near_4 = calc_negative_diff_dates(code,False,date,-4)
            # #print(date_near_4)
            # clf.fit(np.arange(5).reshape(-1,1),code_df['ma20'].loc[date_near_4:date])
            # k_20 = clf.coef_
            # print("S2:最近5日的20日线拟合的斜率：%.2f" % clf.coef_)
            # clf.fit(np.arange(get_diff_dates(code,date_C,date)).reshape(-1,1),code_df['close'].loc[date_C:date])
            # k_CD = clf.coef_
            # print("S2:从C点到当日日线收盘价拟合的斜率：%.2f" % clf.coef_)
            #
            #
            # if change_rate_AB < 50 or change_rate_BC < -30 or change_rate_BC > 0\
            #     or k_20 < -0.1 or k_CD < -0.1 \
            #     or change_rate_BD > 5:
            #     print("S2:形态不满足量化条件")
            #     continue

            #第三步，成交量判断


            code_data_s["date"] = date
            code_data_s["code"] = code
            code_data_s["name"] = get_code_name(code,False)
            code_data_s["date_A"] = date_A
            code_data_s["date_B"] = date_B
            code_data_s["date_C"] = date_C
            code_data_s["avg_2"] = avg_2
            code_data_s["avg_3"] = avg_3
            code_data_s["change_rate_AB"] = change_rate_AB
            code_data_s["diff_dates"] = diff_dates
            code_data_s["daily_change_rate_AB"] = daily_change_rate_AB
            code_data_s["ratio_above_20_AB"] = ratio_above_20_AB
            code_data_s["ratio_positive_AB"] = ratio_positive_AB
            code_data_s["change_rate_above_5_days_AB"] = int(change_rate_above_5)
            code_data_s["change_rate_above_5_ratio_AB"] = change_rate_above_5_ratio_AB
            code_data_s["change_rate_below_N5_days_AB"] = int(change_rate_below_N5)
            code_data_s["change_rate_below_N5_ratio_AB"] = change_rate_below_N5_ratio_AB
            code_data_s["var_AB"] = var_AB
            code_data_s["change_rate_mean_AB"] = change_rate_mean_AB
            code_data_s["positive_continue_value"] = positive_continue_value
            code_data_s["negative_continue_value"] = negative_continue_value
            code_data_s["amount_mean_AB"] = round(amount_mean_AB/1E8,2)
            code_data_s["amount_mean_CD"] = round(amount_mean_CD/1E8,2)
            code_data_s["positive_mean_amount"] = round(positive_mean_amount/1E8,2)
            code_data_s["negative_mean_amount"] = round(negative_mean_amount/1E8,2)


            #插入其他一些辅助的特征数据
            feature_dict = insert_feature_data_at_date(code,date)
            code_data_s.update(feature_dict)

            option_codes_dict[code] = code_data_s

            #print(code_data_s)

            #作图
            # code_df.plot(title='close', y=['close',"ma20"], kind='line')
            # plt.plot(extrem_max_index, close_np[extrem_max_index], 'o')
            # plt.plot(extrem_min_index, close_np[extrem_min_index], '+')
            # for x, y in zip(extrem_max_index, close_np[extrem_max_index]):
            #     plt.text(x, y + 0.3, '%s' % (code_df.index[x]), ha='center', va='bottom', fontsize=10.5)
            # for x, y in zip(extrem_min_index, close_np[extrem_min_index]):
            #     plt.text(x, y + 0.3, '%s' % (code_df.index[x]), ha='center', va='bottom', fontsize=10.5)
            # plt.show()

        except:
            print("股票 %s,计算趋势指标是错误，日期：%s" % (code,date))

    end_time = time.time()
    print("日期：%s,候选股票：%s,耗时：%.2f"% (date,option_codes_dict.keys(),(end_time - start_time)))
    return option_codes_dict




if __name__ == '__main__':
    pd.set_option('display.width', 130)
    pd.set_option('display.max_columns', 130)
    pd.set_option('display.max_colwidth', 130)

    tp = TrendingSpeedUpStockPool(strategy_name="trending_speedup", begin_date="2014-01-01",end_date="2019-06-18",interval=1)
    tp.export_feature_data()
    #tp.train_data()
    #tp.multi_get_trending_speedup_stock("2014-02-18")
    #tp.get_option_stocks()
    #result = get_trending_speedup_stock_at_date(codes = ['002642'],date="2014-02-18")
    #print(result[1])
    # all_dates = get_trading_dates("2014-01-01", "2019-06-18")
    # for date in all_dates:
    #     tp.fiilup_future_result_at_date(date)
    #     tp.fillup_public_feature_data_at_date(date)
